package cn.ty.acl.controller;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.NotBlank;

import cn.summit.captcha.service.CaptchaCodeCreator;
import cn.ty.acl.constants.AclConstants;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;

import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

/**
 * 验证码
 *
 * @author summit
 * @since 2021/6/22 13:43
 */
@RestController
@RequestMapping("/login")
@Validated
@RequiredArgsConstructor
@Slf4j
@Api(value = "/login", tags = "登录")
public class CaptchaController {

	private final CaptchaCodeCreator captchaCodeCreator;

	private final StringRedisTemplate stringRedisTemplate;


	@GetMapping("/captcha")
	@ApiOperation("获取验证码")
	public void captcha(@NotBlank @RequestParam("captchaKey") String captchaKey, HttpServletResponse response) throws IOException {
		String code = captchaCodeCreator.getResponseImage(response.getOutputStream());
		log.info("当前验证码id[{}],code[{}]", captchaKey, code);
		stringRedisTemplate.opsForValue().set(AclConstants.CAPTCHA_PREFIX + captchaKey, code, 10, TimeUnit.MINUTES);
	}
}
